package com.yf.dxapp.module.app.sms;

import cn.iocoder.yudao.framework.common.exception.ServiceException;
import com.yf.dxapp.module.app.consts.MyConst;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Random;

@Service
public class SmsService {

    @Resource
    private CaptchaRedisDao captchaRedisDao;

    @Resource
    private SmsHandler smsHandler;

    public void sendCaptcha(String phone){
        String captcha = initCaptcha();
        smsHandler.senCaptcha(phone,captcha);
        captchaRedisDao.setCaptcha(phone,captcha);
    }

    public void verifyCaptcha(String phone,String captcha){

        String text = captchaRedisDao.getCaptcha(phone);
        if(!StringUtils.hasText(captcha)||!StringUtils.hasText(text)||!text.equals(captcha)){
            throw new ServiceException(MyConst.BUS_ERROR_CODE,"验证码错误!");
        }
    }

    private String initCaptcha() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder(4);
        for (int i = 0; i < 4; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

}
